package com.myweb;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author DTIT
 */
@WebFilter("*.jsp")
public class SessionCheckFilter implements Filter {

  private String login;

  @Override
  public void init(FilterConfig fc) throws ServletException {
    login = fc.getServletContext().getContextPath() + "/login.jsp";
  }

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain fc) throws IOException, ServletException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;
    String reqWith = req.getHeader("X-Requested-With");
    if (req.getSession().getAttribute(MyWeb.KEY_USER) == null && !req.getRequestURI().equals(login)) {
      if (reqWith != null && reqWith.equals("XMLHttpRequest")) {
        res.setHeader("X-Redirect", login);
      } else {
        res.sendRedirect(login);
      }
    } else {
      fc.doFilter(request, response);
    }
  }

  @Override
  public void destroy() {
    
  }
}
